package com.leixiaoqiao.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//编码过滤器
@WebFilter("/*")
public class CodeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        //对request对象进行增强(getParameter方法进行增强)

        //将代理对象传递到控制器中，而控制器中调用的方法，应该是代理对象的方法(只需在代理对象的方法中进行业务控制)
        HttpServletRequest req = (HttpServletRequest)Proxy.newProxyInstance(request.getClass().getClassLoader(), request.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                //判断该方法是否是getParameter方法
                if("getParameter".equals(method.getName())){
                    //判断请求是否是post请求
                    String method1 = request.getMethod();
                    if("post".equalsIgnoreCase(method1)){
                        //则进行增强
                        String invoke = (String)method.invoke(request, args);
                        if(invoke !=null) {
                            String value = new String(invoke.getBytes("ISO-8859-1"), "utf-8");
                            return value;
                        }
                        return invoke;
                    }
                }
                return method.invoke(request, args);
            }
        });
        //放行
        filterChain.doFilter(req,response);
    }

    @Override
    public void destroy() {

    }
}
